import React, { useState, useEffect } from 'react';

interface BackTopProps {
  target?: string; // 目标元素的选择器
  visibilityHeight?: number; // 滚动高度达到此参数值才出现
  right?: number; // 距离右侧的距离
  bottom?: number; // 距离底部的距离
}

const BackTop: React.FC<BackTopProps> = ({ 
  target = '#chat-box', 
  visibilityHeight = 400,
  right = 20,
  bottom = 20
}) => {
  const [visible, setVisible] = useState(false);
  
  useEffect(() => {
    const targetElement = document.querySelector(target);
    
    if (!targetElement) return;
    
    const scrollHandler = () => {
      setVisible(targetElement.scrollTop > visibilityHeight);
    };
    
    targetElement.addEventListener('scroll', scrollHandler);
    
    return () => {
      targetElement.removeEventListener('scroll', scrollHandler);
    };
  }, [target, visibilityHeight]);
  
  const scrollToTop = () => {
    const targetElement = document.querySelector(target);
    
    if (!targetElement) return;
    
    targetElement.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
  };
  
  if (!visible) return null;
  
  return (
    <div 
      className="back-top" 
      onClick={scrollToTop} 
      title="返回顶部"
      style={{ right: `${right}px`, bottom: `${bottom}px` }}
    >
      <svg 
        xmlns="http://www.w3.org/2000/svg" 
        width="24" 
        height="24" 
        viewBox="0 0 24 24" 
        fill="none" 
        stroke="currentColor" 
        strokeWidth="2" 
        strokeLinecap="round" 
        strokeLinejoin="round"
      >
        <polyline points="18 15 12 9 6 15"></polyline>
      </svg>
    </div>
  );
};

export default BackTop; 